package com.braska.grave.netty.listener;

import com.braska.grave.netty.manager.NettyChannelManager;
import com.google.common.collect.Lists;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.EventLoop;

import java.util.concurrent.TimeUnit;

/**
 * @author shenyuhang
 * @date 2020/4/22
 **/
public class ConnectionListener implements ChannelFutureListener {
    private final static Integer DEFAULT_RETRY_COUNT = 5;
    private NettyChannelManager manager;
    private String address;

    public ConnectionListener(NettyChannelManager manager, String address) {
        this.manager = manager;
        this.address = address;
    }

    @Override
    public void operationComplete(ChannelFuture channelFuture) throws Exception {
        if (!channelFuture.isSuccess()) {
            final EventLoop loop = channelFuture.channel().eventLoop();
            loop.schedule(new Runnable() {
                @Override
                public void run() {
                    System.err.println("服务端链接不上，开始重连操作...");
                    manager.refresh(
                            Lists.newArrayList(address)
                    );
                }
            }, 1L, TimeUnit.SECONDS);
        } else {
            System.out.println("服务端链接成功...");
        }
    }
}
